/**
 * Created by FreezeSoul on 2016/4/7.
 */
define([
    "app/core/base",
    "app/core/util",
    "../commonMeta",
    "jquery",
    "underscore",
    'loglevel',
    'jqueryTmpl',
    'jQueryUUID'
], function (Chart, Util, Meta, $, _, log) {

    var property = {
        config: "property",
        option: [
            {
                group: '基础',
                id: 'LabelInitText',
                name: '初始文本',
                enable: false,
                type: 'text',
                value: '',
                default: '',
                link: 'text',
                tooltip: '文本标签初始值'
            },
            {
                group: '基础',
                id: 'LabelFormatNumber',
                name: '数值格式化',
                enable: false,
                type: 'checked',
                value: false,
                default: false,
                link: 'formatNumber',
                tooltip: '内容数值格式化，3位一逗号，常用绑定:“###,###”'
            },
            {
                group: '基础',
                id: 'LabelTextPrefix',
                name: '文本前缀',
                enable: false,
                type: 'text',
                value: '',
                default: '',
                link: 'textPrefix',
                tooltip: '文本前缀'
            },
            {
                group: '基础',
                id: 'LabelTextPostfix',
                name: '文本后缀',
                enable: false,
                type: 'text',
                value: '',
                default: '',
                link: 'textPostfix',
                tooltip: '文本后缀'
            },
            {
                group: '基础',
                id: 'LabelFontSize',
                name: '字体大小',
                enable: false,
                type: 'number',
                value: 14,
                default: 14,
                link: 'fontSize',
                tooltip: '文本字体大小'
            },
            {
                group: '基础',
                id: 'LabelFontWeight',
                name: '字体厚度',
                enable: false,
                type: 'select',
                value: 'normal',
                default: 'normal',
                data: [{
                    value: 'normal',
                    text: 'normal'
                }, {
                    value: 'lighter',
                    text: 'lighter'
                }, {
                    value: 'bolder',
                    text: 'bolder'
                }],
                link: 'fontWeight',
                tooltip: '字体厚度'
            },
            {
                group: '基础',
                id: 'LabelFontFamily',
                name: '字体样式',
                enable: false,
                type: 'select',
                value: 'Microsoft YaHei',
                default: 'Microsoft YaHei',
                data: [{
                    value: 'Microsoft YaHei',
                    text: '微软雅黑体'
                }, {
                    value: 'KaiTi',
                    text: '楷体'
                }, {
                    value: 'FangSong',
                    text: '仿宋'
                }, {
                    value: 'NSimSun',
                    text: '新宋体'
                }, {
                    value: 'SimSun',
                    text: '宋体'
                }, {
                    value: 'SimHei',
                    text: '黑体'
                }],
                link: 'fontFamily',
                tooltip: '字体样式'
            },
            {
                group: '基础',
                id: 'LabelTextAlign',
                name: '对齐方式',
                enable: false,
                type: 'select',
                value: 'left',
                default: 'left',
                data: [{
                    value: 'left',
                    text: 'left'
                }, {
                    value: 'right',
                    text: 'right'
                }, {
                    value: 'center',
                    text: 'center'
                }],
                link: 'textAlign',
                tooltip: '字体对齐方式'
            },
            {
                group: '基础',
                id: 'LabelFontColor',
                name: '字体颜色',
                enable: false,
                type: 'color',
                value: '#000000',
                default: '#000000',
                link: 'fontColor',
                tooltip: '文本字体颜色'
            },
            {
                group: '基础',
                id: 'LabelBorderPadding',
                name: '内边距值',
                enable: false,
                type: 'padding',
                value: [5, 5, 5, 5],
                default: [5, 5, 5, 5],
                link: 'padding',
                tooltip: '文本内边距值'
            },
            {
                group: '基础',
                id: 'LabelBorderWidth',
                name: '边框宽度',
                enable: false,
                type: 'number',
                value: 1,
                default: 1,
                link: 'borderWidth',
                tooltip: '文本边框宽度'
            },
            {
                group: '基础',
                id: 'LabelBorderStyle',
                name: '边框样式',
                enable: false,
                type: 'select',
                value: 'solid',
                default: 'solid',
                data: [{
                    value: 'dotted',
                    text: '点线边框'
                }, {
                    value: 'dashed',
                    text: '虚线边框'
                }, {
                    value: 'solid',
                    text: '实线边框'
                }, {
                    value: 'double',
                    text: '两个边框'
                }, {
                    value: 'groove',
                    text: '3D沟槽边框'
                }, {
                    value: 'ridge',
                    text: '3D脊边框'
                }, {
                    value: 'inset',
                    text: '3D嵌入边框'
                }, {
                    value: 'outset',
                    text: '3D突出边框'
                }],
                link: 'borderStyle',
                tooltip: '文本边框样式'
            },
            {
                group: '基础',
                id: 'LabelBorderColor',
                name: '边框颜色',
                enable: false,
                type: 'color',
                value: '#000000',
                default: '#000000',
                link: 'borderColor',
                tooltip: '文本边框颜色'
            },
            {
                group: '基础',
                id: 'LabelBackColor',
                name: '背景颜色',
                enable: false,
                type: 'color',
                value: 'transparent',
                default: 'transparent',
                link: 'backColor',
                tooltip: '文本背景颜色，透明色transparent'
            },
            {
                group: '基础',
                id: 'LabelHoverAnimationList',
                name: '鼠标响应',
                enable: false,
                type: 'select',
                value: '',
                default: '',
                data: [{
                    value: '',
                    text: '无效果'
                }, {value: 'bounce', text: 'bounce'},
                    {value: 'flash', text: 'flash'},
                    {value: 'pulse', text: 'pulse'},
                    {value: 'rubberBand', text: 'rubberBand'},
                    {value: 'shake', text: 'shake'},
                    {value: 'headShake', text: 'headShake'},
                    {value: 'swing', text: 'swing'},
                    {value: 'tada', text: 'tada'},
                    {value: 'wobble', text: 'wobble'},
                    {value: 'jello', text: 'jello'},
                    {value: 'bounceIn', text: 'bounceIn'},
                    {value: 'bounceInDown', text: 'bounceInDown'},
                    {value: 'bounceInLeft', text: 'bounceInLeft'},
                    {value: 'bounceInRight', text: 'bounceInRight'},
                    {value: 'bounceInUp', text: 'bounceInUp'},
                    {value: 'bounceOut', text: 'bounceOut'},
                    {value: 'bounceOutDown', text: 'bounceOutDown'},
                    {value: 'bounceOutLeft', text: 'bounceOutLeft'},
                    {value: 'bounceOutRight', text: 'bounceOutRight'},
                    {value: 'bounceOutUp', text: 'bounceOutUp'},
                    {value: 'fadeIn', text: 'fadeIn'},
                    {value: 'fadeInDown', text: 'fadeInDown'},
                    {value: 'fadeInDownBig', text: 'fadeInDownBig'},
                    {value: 'fadeInLeft', text: 'fadeInLeft'},
                    {value: 'fadeInLeftBig', text: 'fadeInLeftBig'},
                    {value: 'fadeInRight', text: 'fadeInRight'},
                    {value: 'fadeInRightBig', text: 'fadeInRightBig'},
                    {value: 'fadeInUp', text: 'fadeInUp'},
                    {value: 'fadeInUpBig', text: 'fadeInUpBig'},
                    {value: 'fadeOut', text: 'fadeOut'},
                    {value: 'fadeOutDown', text: 'fadeOutDown'},
                    {value: 'fadeOutDownBig', text: 'fadeOutDownBig'},
                    {value: 'fadeOutLeft', text: 'fadeOutLeft'},
                    {value: 'fadeOutLeftBig', text: 'fadeOutLeftBig'},
                    {value: 'fadeOutRight', text: 'fadeOutRight'},
                    {value: 'fadeOutRightBig', text: 'fadeOutRightBig'},
                    {value: 'fadeOutUp', text: 'fadeOutUp'},
                    {value: 'fadeOutUpBig', text: 'fadeOutUpBig'},
                    {value: 'flipInX', text: 'flipInX'},
                    {value: 'flipInY', text: 'flipInY'},
                    {value: 'flipOutX', text: 'flipOutX'},
                    {value: 'flipOutY', text: 'flipOutY'},
                    {value: 'lightSpeedIn', text: 'lightSpeedIn'},
                    {value: 'lightSpeedOut', text: 'lightSpeedOut'},
                    {value: 'rotateIn', text: 'rotateIn'},
                    {value: 'rotateInDownLeft', text: 'rotateInDownLeft'},
                    {value: 'rotateInDownRight', text: 'rotateInDownRight'},
                    {value: 'rotateInUpLeft', text: 'rotateInUpLeft'},
                    {value: 'rotateInUpRight', text: 'rotateInUpRight'},
                    {value: 'rotateOut', text: 'rotateOut'},
                    {value: 'rotateOutDownLeft', text: 'rotateOutDownLeft'},
                    {value: 'rotateOutDownRight', text: 'rotateOutDownRight'},
                    {value: 'rotateOutUpLeft', text: 'rotateOutUpLeft'},
                    {value: 'rotateOutUpRight', text: 'rotateOutUpRight'},
                    {value: 'hinge', text: 'hinge'},
                    {value: 'jackInTheBox', text: 'jackInTheBox'},
                    {value: 'rollIn', text: 'rollIn'},
                    {value: 'rollOut', text: 'rollOut'},
                    {value: 'zoomIn', text: 'zoomIn'},
                    {value: 'zoomInDown', text: 'zoomInDown'},
                    {value: 'zoomInLeft', text: 'zoomInLeft'},
                    {value: 'zoomInRight', text: 'zoomInRight'},
                    {value: 'zoomInUp', text: 'zoomInUp'},
                    {value: 'zoomOut', text: 'zoomOut'},
                    {value: 'zoomOutDown', text: 'zoomOutDown'},
                    {value: 'zoomOutLeft', text: 'zoomOutLeft'},
                    {value: 'zoomOutRight', text: 'zoomOutRight'},
                    {value: 'zoomOutUp', text: 'zoomOutUp'},
                    {value: 'slideInDown', text: 'slideInDown'},
                    {value: 'slideInLeft', text: 'slideInLeft'},
                    {value: 'slideInRight', text: 'slideInRight'},
                    {value: 'slideInUp', text: 'slideInUp'},
                    {value: 'slideOutDown', text: 'slideOutDown'},
                    {value: 'slideOutLeft', text: 'slideOutLeft'},
                    {value: 'slideOutRight', text: 'slideOutRight'},
                    {value: 'slideOutUp', text: 'slideOutUp'}],
                link: 'hoverAnimation',
                tooltip: '鼠标响应动画'
            },
            {
                group: '绑定',
                id: 'LabelBangDing',
                name: '绑定文本',
                enable: false,
                type: 'textBinding',
                dataset: '',
                ctype: 'all',
                column: {},
                tooltip: '文本绑定'
            },
            {
                group: '绑定',
                id: 'LabelFilterName',
                name: '过滤列名称',
                enable: false,
                type: 'text',
                value: '',
                default: '',
                link: 'filterName',
                tooltip: '绑定数据集，客户端过滤字段列名称'
            },
            {
                group: '绑定',
                id: 'LabelFilterValue',
                name: '过滤列默认值',
                enable: false,
                type: 'text',
                value: '',
                default: '',
                link: 'filterValue',
                tooltip: '绑定数据集，客户端过滤字段默认值'
            },
            {
                group: '事件',
                id: 'LabelClick',
                name: '点击跳转事件',
                enable: true,
                type: 'pivotEvent',
                value: {
                    Event: "LabelClick",
                    Params: [
                        {Value: "Text", Name: "文本"}
                    ]
                },
                tooltip: '点击跳转事件，钻取设置'
            },
            {
                group: '事件',
                id: 'LabelClickJsEval',
                name: '点击执行脚本',
                enable: false,
                type: 'script',
                value: '',
                default: '',
                link: 'clickScript',
                tooltip: '点击执行脚本，可定制复杂的JS操作'
            }
        ].concat($.extend(true, [], Meta.commonProperties)),
        MapOption: function (option) {
            Util.linkOption(this.option, option);
        }
    };

    var label = Chart.extend({
        constructor: function (layout) {
            this._layout = layout;
            this._lastdata = null;
            this._element = null;
            this._container = null;
            this._option = {
                Series: [],
                Events: [],
                Extend: $.extend(true, {}, property),
                Option: {
                    uuid: '',
                    class: '',
                    display: true,
                    text: "标签控件",
                    formatNumber: false,
                    textPrefix: "",
                    textPostfix: "",
                    padding: [5, 5, 5, 5],
                    fontSize: 14,
                    fontColor: "#000000",
                    fontFamily: "",
                    fontWeight: "",
                    textAlign: "",
                    borderWidth: 1,
                    borderStyle: "",
                    borderColor: "#000000",
                    backColor: "transparent",
                    hoverAnimation: "",
                    clickScript: '',
                    initScript: '',
                    disposeScript: '',
                    parseDataScript: '',
                    lazyLoadData: false,
                    __beforeInitScript: '',
                    __afterInitScript: '',
                    __beforeSetOptionScript: '',
                    __afterSetOptionScript: '',
                    __beforeSetDataScript: '',
                    __afterSetDataScript: '',
                    __beforeGetOptionScript: '',
                    __afterGetOptionScript: '',
                    __beforeDisposeScript: '',
                    __afterDisposeScript: ''
                }
            };
        },
        init: function (element) {
            try {
                this._uuid = $.uuid();
                this._container = element;
            } catch (e) {
                log.error(e);
            }
        },
        _readProperty: function () {
            try {
                if (!this._option.Extend) return;
                Util.deepMapOption(property, this._option.Extend, this._option.Option);
            } catch (e) {
                log.error(e);
            }
        },
        _render: function (option) {
            var newText = option.text;
            if(newText === null){
                newText = "";
            }
            if (option.formatNumber === true) {
                newText = Util.formatNumber(newText);
            }
            if (option.textPrefix) {
                newText = option.textPrefix + newText;
            }
            if (option.textPostfix) {
                newText = newText + option.textPostfix;
            }
            var $element = $.tmpl('<div id="${id}" class="label-text">${text}</div>', {
                id: this._uuid,
                text: newText
            });
            if (option.fontSize && option.fontSize > 0) {
                $element.css("font-size", option.fontSize + "px")
            }
            if (option.fontWeight) {
                $element.css("font-weight", option.fontWeight)
            }
            if ($.isArray(option.padding) && option.padding.length === 4) {
                if (option.padding[0] && option.padding[0] > 0)
                    $element.css("padding-top", option.padding[0]);
                if (option.padding[1] && option.padding[1] > 0)
                    $element.css("padding-right", option.padding[1]);
                if (option.padding[2] && option.padding[2] > 0)
                    $element.css("padding-bottom", option.padding[2]);
                if (option.padding[3] && option.padding[3] > 0)
                    $element.css("padding-left", option.padding[3]);
            }
            if (option.fontColor) {
                $element.css("color", option.fontColor)
            }
            if (option.textAlign) {
                $element.css("text-align", option.textAlign)
            }
            if (option.fontFamily) {
                $element.css("font-family", option.fontFamily)
            }
            if (option.borderWidth && option.borderWidth > 0) {
                $element.css("border-width", option.borderWidth + "px")
            }
            if (option.borderColor) {
                $element.css("border-color", option.borderColor)
            }
            if (option.borderStyle) {
                $element.css("border-style", option.borderStyle)
            }
            if (option.backColor) {
                $element.css("background-color", option.backColor)
            }
            if (option.hoverAnimation) {
                $element.hover(
                    function () {
                        if ($element.hasClass("animated")) return;
                        $element.addClass("animated " + option.hoverAnimation)
                            .one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function () {
                                $element.removeClass("animated " + option.hoverAnimation)
                            });
                    }, function () {
                    }
                );
            }
            $(this._container).empty();
            $element.appendTo(this._container);
            this._bindEvent($element);

            //Util.setCommonMeta(this, this._container, this._option.Option);
            //Util.initChartLifeTime(this, this._container, this._option.Option);

            return $element;
        },
        _bindEvent: function (element) {
            var _this = this;
            $(element).on("click", function (e) {
                if (_this._layout
                    && _this._layout.navigate
                    && _this._option.Events
                    && _this._option.Events.length > 0) {

                    var registerEvent = _.findWhere(_this._option.Events, {Event: "LabelClick"});
                    if (registerEvent) {
                        var pageId = registerEvent.PageId;
                        var params = registerEvent.Params;
                        var args = [];
                        var dParam = _.findWhere(params, {Name: "文本"});
                        if (dParam && dParam.ParamName) {
                            args.push({
                                ParamName: dParam.ParamName,
                                ParamValue: $(element).find(".label-text").text()
                            });
                        }
                        _this._layout.navigate(pageId, args);
                    }
                    e.preventDefault();
                }

                if (_this._option.Option
                    && _this._option.Option.clickScript) {
                    Util.evalJavaScript(_this, _this._option.Option.clickScript);
                }
            });

            if (!this._filterDataHandle) {
                this._filterDataHandle = function (params) {
                    _this.filterDataHandle.call(_this, params);
                };
            }
            this._layout.removeListener("filterData", this._filterDataHandle);
            this._layout.addListener("filterData", this._filterDataHandle);
        },
        filterDataHandle: function (params) {
            var _this = this;
            var flag = false;
            var filterColumn = _.findWhere(this._option.Extend.option, {name: '过滤列名称'});
            var filterValue = _.findWhere(this._option.Extend.option, {name: '过滤列默认值'});

            if (filterColumn && filterValue
                && filterColumn.enable && filterValue.enable
                && filterColumn.value !== "" && filterValue.value !== ""
            ) {
                for (var prop in params) {
                    if (!params.hasOwnProperty(prop)) continue;
                    if (filterColumn.value === prop) {
                        filterValue.value = params[prop];
                        flag = true;
                    }
                }
            }
            if (flag && _this._lastdata) {
                _this.setData(_this._lastdata);
            }
        },
        example: function () {
            try {
                this._element = this._render(this._option.Option);
            } catch (e) {
                log.error(e);
            }
        },
        _bindData: function (data) {
            var bindProperty = _.findWhere(this._option.Extend.option, {type: 'textBinding'});
            if (!bindProperty || !bindProperty.dataset) return;
            var dataSetCode = bindProperty.dataset;
            var table = data[dataSetCode];
            table = this._filterTable(this._option.Extend.option, table);
            if (table && table.length > 0 && bindProperty.column) {
                var row = table[0];
                var columnName = bindProperty.column.ColumnName;
                if (columnName) {
                    this._option.Option.text = row[columnName];
                }
            }
        },
        _filterTable: function (option, table) {
            var filterColumn = _.findWhere(option, {name: '过滤列名称'});
            var filterValue = _.findWhere(option, {name: '过滤列默认值'});

            if (table && filterColumn && filterValue
                && filterColumn.enable && filterValue.enable
                && filterColumn.value !== "" && filterValue.value !== ""
            ) {
                var tableCopy = _.map(table, _.clone);
                return _.filter(tableCopy, function (row) {
                    return row[filterColumn.value] === filterValue.value;
                });
            }
            return table;
        },
        setData: function (data) {
            try {
                this._lastdata = data;
                this._readProperty();
                //data = Util.parseDataChartLifTime(this, this._container, this._option.Option, data);
                if (data
                    && this._option.Binding
                    && this._option.Binding.length > 0
                    && this._option.Extend
                ) {
                    this._bindData(data);
                }
                this._element = this._render(this._option.Option);
            } catch (e) {
                log.error(e);
            }
        },
        setOption: function (option) {
            try {
                return this._option = $.extend(true, {}, option);
            } catch (e) {
                log.error(e);
            }
        },
        getOption: function () {
            try {
                this._readProperty();
            } catch (e) {
                log.error(e);
            }
            return this._option;
        },
        setTheme: function (theme) {
            try {
            } catch (e) {
                log.error(e);
            }
        },
        resize: function () {
            try {
            } catch (e) {
                log.error(e);
            }
        },
        showLoading: function () {
            try {
                if (this._layout && this._layout.showLoading) {
                    this._layout.showLoading(this);
                }
            } catch (e) {
                log.error(e);
            }
        },
        hideLoading: function () {
            try {
                if (this._layout && this._layout.hideLoading) {
                    this._layout.hideLoading(this);
                }
            } catch (e) {
                log.error(e);
            }
        },
        dispose: function () {
            try {
                $(this._element).off().remove();
                this._layout.removeListener("filterData", this._filterDataHandle);
                //Util.disposeChartLifeTime(this, this._container, this._option.Option);
            } catch (e) {
                log.error(e);
            }
        },
        getElement: function () {
            return this._element;
        },
        getChart: function () {
            return this._element;
        }
    });

    return {
        Chart: label,
        Property: property
    };
});